package com.itcc.dao.impl;

import com.itcc.dao.UserDao;
import com.itcc.entity.User;
import com.itcc.utils.C3P0Utils;
import com.itcc.utils.Constants;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

//数据库访问实现类
public class UserDaoImpl implements UserDao {

    @Override
    public User selectUserByUname(String username) throws SQLException {

        QueryRunner queryRunner=new QueryRunner(C3P0Utils.getDataSource());
        String sql="select u_id as uid,u_name as username,u_password as upassword," +
                "u_sex as usex, u_status as ustatus,u_code as code,u_email as email," +
                "u_role as urole from user where u_name=?";
        User user=queryRunner.query(sql, new BeanHandler<User>(User.class),username) ;
        return user;
    }

    @Override
    public int insertUser(User user) throws SQLException {
        QueryRunner queryRunner=new QueryRunner(C3P0Utils.getDataSource());
        String sql="insert into user(u_name,u_password,u_sex,u_status," +
                "u_code,u_email,u_role) values (?,?,?,?,?,?,?)" ;
        int rows = queryRunner.update(sql, user.getUsername(), user.getUpassword(), user.getUsex(),
                user.getUstatus(), user.getCode(), user.getEmail(), user.getUrole());
        return rows;
    }

    @Override
    public User selectUserbyCode(String code) throws SQLException {
        QueryRunner queryRunner=new QueryRunner(C3P0Utils.getDataSource());
        String sql="select u_id as uid,u_name as username,u_password as upassword," +
                "u_sex as usex, u_status as ustatus,u_code as code,u_email as email," +
                "u_role as urole from user where code=?";
        User user=queryRunner.query(sql, new BeanHandler<User>(User.class),code) ;
        return user;
    }

    @Override
    public int updateStatusByUid(int uid) throws SQLException {
        QueryRunner queryRunner=new QueryRunner(C3P0Utils.getDataSource());
        String sql="update user set u_code=? where u_id=?";
        int row=queryRunner.update(sql, Constants.USER_ACTIVE,uid);
        return row;
    }

    @Override
    public List<User> findAllUser() throws SQLException {
        QueryRunner queryRunner=new QueryRunner(C3P0Utils.getDataSource());

        String sql="select u_id as uid,u_name as username,u_password as upassword," +
                "u_sex as usex, u_status as ustatus,u_code as code,u_email as email," +
                "u_role as urole from user ;";

        List<User> list = queryRunner.query(sql, new BeanListHandler<User>(User.class));
        return list;
    }
}
